package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.exception.CustException;
import com.heima.feigns.article.ArticleFeign;
import com.heima.feigns.wemedia.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.constants.AdminConstants;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname> implements ApUserRealnameService {

    //根据状态查询需要认证相关的用户信息

    @Override
    public ResponseResult loadListByStatus(AuthDto dto) {
        //1 参数校验
        if (dto == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();

        //2 执行查询
        IPage<ApUserRealname> page = new Page<>(dto.getPage(), dto.getSize());
        LambdaQueryWrapper<ApUserRealname> wrapper = new LambdaQueryWrapper();


        /**
         * 状态
             0 创建中
             1 待审核
             2 审核失败
             9 审核通过
         */

        if (dto.getStatus() != null) {
            wrapper.eq(ApUserRealname::getStatus, dto.getStatus());
        }

        IPage<ApUserRealname> pageResult = page(page, wrapper);

        //3 结果封装
        return new PageResponseResult(dto.getPage(),dto.getSize(),
                (int)pageResult.getTotal(), pageResult.getRecords());
    }


    @Autowired
    ApUserMapper apUserMapper;

    /**
     * 认证用户
     * @param dto
     * @param status 2 审核失败   9 审核成功
     * @return
     */
    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public ResponseResult authPass(AuthDto dto, Short status) {
        //1 检查参数
        if (dto == null || dto.getId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2 判断当前用户合法性
        ApUserRealname apUserRealname = getOne(Wrappers.<ApUserRealname>lambdaQuery()
                .eq(ApUserRealname::getId,dto.getId())
                .eq(ApUserRealname::getStatus, 1)  // ** 未审核用户
        );
        if (apUserRealname == null) {
            CustException.cust( AppHttpCodeEnum.APUSERREALNAME_DATANOTEXIST_ERROR );
        }
        // APUser Id
        Integer apUserId = apUserRealname.getUserId();
        ApUser apUser = apUserMapper.selectOne(
                Wrappers.<ApUser>lambdaQuery()
                .eq(ApUser::getId, apUserId)
                .eq(ApUser::getStatus, 0)
        );
        if (apUser == null) {
            CustException.cust( AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST );
        }
        //3 修改ApUserRealname的状态
        apUserRealname.setId(dto.getId());
        apUserRealname.setStatus(status);
        apUserRealname.setUpdatedTime(new Date());
        if (StringUtils.isNotBlank(dto.getMsg())) {
            apUserRealname.setReason(dto.getMsg());
        }
        updateById(apUserRealname);
//        int i = 1 / 0;


        //4 如果 status 审核通过
        if (AdminConstants.PASS_AUTH.equals(status)) {
            //4.1 Feign创建 自媒体人账号
            WmUser wmUser = createWmUser(dto, apUser);
            if (wmUser == null) {
                CustException.cust( AppHttpCodeEnum.WMUSER_ADD_ERROR );
            }

            //4.2 Feign创建 文章作者账号
           Boolean flag =  createApAuthor(wmUser);
            if (!flag) {
                CustException.cust( AppHttpCodeEnum.APAUTHOR_ADD_ERROR );
            }

            // 5 修改 apUser flag 为 自媒体人
            apUser.setFlag((short) 1);
            apUserMapper.updateById(apUser);
        }


        int i = 1 / 0;

        //6 返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    ArticleFeign articleFeign;

    //创建 文章作者的信息
    private Boolean createApAuthor(WmUser wmUser) {

        //1 查询文章作者信息
        ApAuthor apAuthor = articleFeign.findByUserId(wmUser.getApUserId());
        if (apAuthor == null) {
            apAuthor = new ApAuthor();
            apAuthor.setWmUserId(wmUser.getId());
            apAuthor.setUserId(wmUser.getApUserId());
            apAuthor.setType(2);
            apAuthor.setName(wmUser.getName());
            apAuthor.setCreatedTime(new Date());

            ResponseResult result = articleFeign.save(apAuthor);
            // code=0
            if (result.getCode() == 0) {
                return true;
            }
        }

        return false;

    }

    @Autowired
    WemediaFeign wemediaFeign;

    //创建 WmUser 自媒体账号
     //自媒体用户的 账号和密码 默认规则是：和APP用户保存一致
    private WmUser createWmUser(AuthDto dto, ApUser apUser) {

        //1 查询自媒体人
        WmUser wmUser = wemediaFeign.findByName(apUser.getName());
        if (wmUser == null) {
            wmUser = new WmUser();
            wmUser.setApUserId(apUser.getId());
            wmUser.setName(apUser.getName());
            wmUser.setPassword(apUser.getPassword());
            wmUser.setSalt(apUser.getSalt());
            wmUser.setPhone(apUser.getPhone());
            wmUser.setCreatedTime(new Date());
            wmUser.setType(0); // 个人
            wmUser.setStatus(AdminConstants.PASS_AUTH.intValue());

            wmUser = wemediaFeign.save(wmUser);

            if (wmUser.getId() != null) {
                return wmUser;
            }

        }

        return null;

    }
}
